var moment = require('moment');  // 日期格式化
var fs = require('fs');
var path = require('path')
var async = require('async');
var fast = require('fast.js');

var ArrayType = require('ref-array');
var ffi = require("ffi");
var ref = require('ref');
// define the "long[]" type
var LongArray = ArrayType(ref.types.long);

var common = require('../common');
var config = require('../config').getConfig();
var DEFINE = require('../define').getDefine();

var commonUtil = require('../commonUtil');
var pool = require('../mysql');
var mysql = require('mysql');

var GroupObj = require('../pdf/obj/GroupObj');
var FileObj = require('../pdf/obj/FileObj');
var ImageObj = require('../pdf/obj/ImageObj');

var os = require('os');

// 将图片数组组成GroupObj
exports.makeGroupObjFromImageList = function(imageList,w,h){
    var group = new GroupObj();
    group.x =0;
    group.y =0;
    group.w =w;
    group.h =h;

    fast.forEach(imageList, function(item){
        var image = new ImageObj();
        image.x = item.x;
        image.y = item.y;
        image.w = item.w;
        image.h = item.h;
        image.fp = item.pn;
        group.sub.push(image);
    });
    return group;
}
/*
 {		// 模版页的简化数据
     ‘lay’:[0,0,200,100,0],    (数组表示：x,y,宽,高,角度,图片地址)
     ‘edit’:[20,20,160,60,0],
     'layUp':[0,0,200,100,0,'http://xxxxxxx'],
     'layDown':[0,0,160,60,0,'http://xxxxxxx'],
     'bg':[0,0,160,60,0,'http://xxxxxxx'],
     'rootReplaceGroup':{}   // 可替换部分的根GroupObj的json数组
 }
 */
exports.templateSimplifyPageToGroup = function(templateSimplifyPage){
    if(templateSimplifyPage. rootReplaceGroup&& templateSimplifyPage. rootReplaceGroup.sub){
        var file = new FileObj();
        file.x =0;
        file.y =0;
        file.w =templateSimplifyPage.bg[2];
        file.h =templateSimplifyPage.bg[3];
        file.fp = templateSimplifyPage.bg[5];

        templateSimplifyPage. rootReplaceGroup.sub.splice(0,0,file);
        return templateSimplifyPage.rootReplaceGroup;
    }else{
        return null;
    }

}


// 生成作品的每页的缩略图(利用design和template的简化数据去生成)
// serialCallback回调，参数为:
//        error
//        common.PAGE_BACKGROUND_INFO_STRUCT数组
exports.makeImageOfDesignFromSimplify = function(designId,serialCallback) {
    var THIS = this;
    // 从mysql中查询
    function getDataFromDB(designId, dbCallback){
        pool.pool.getConnection(function(err, connection) {

            var sql = "select t1.content,t2.simplify as templateSimplify from MTDesignModel t1, MTTemplateModel t2 where t1.template=t2.id and t1.id=?";
            var sqlValue = [designId];
            var sql = mysql.format(sql, sqlValue);
            console.log(sql);

            // Use the connection
            connection.query(sql, function(error, items) {
                // And done with the connection.
                connection.release();

                if(error){
                    console.log(error);
                    dbCallback(null);
                }else if(items.length==0){
                    dbCallback(null);
                }else{
                    dbCallback(items[0]);
                }
            });
        });
    }
    // 从db取数据并处理
    getDataFromDB(designId, function(item){
        /*
         [// 可替换图片的数据
             {x:1,y:2,rid:3.........},
             {x:1,y:2,rid:3.........}
         ]
         */
        var replacePgsJson = item.content;
        /*
         [{		// 模版页的简化数据
                 ‘lay’:[0,0,200,100,0],    (数组表示：x,y,宽,高,角度,图片地址)
                 ‘edit’:[20,20,160,60,0],
                 'layUp':[0,0,200,100,0,'http://xxxxxxx'],
                 'layDown':[0,0,160,60,0,'http://xxxxxxx'],
                 'bg':[0,0,160,60,0,'http://xxxxxxx'],
                 'rootReplaceGroup':{}   // 可替换部分的根GroupObj的json数组
         }]
         */
        var templateSimplify =JSON.parse( item.templateSimplify);

        // 每页的模版图和布局图的缩放倍数必须保持一致，计算出各自应该缩放的大小
        var imageSizes = config.RECT_IMAGE_OPTIONS;

        var libFunc = THIS.getImageProcessFuncs();

        var imgDirPath =path.join(__dirname,'../../ImageServer/public');
        var relativeDir = '/uploads/' +DEFINE.TIMAGE_TYPE.DPT + '/' +commonUtil.genUpDir();// 存放图片的根文件夹

        // 将所有页组成tasks，串行调用

        var tasks = new Array();
        for (var j = 0; j < templateSimplify.length; j++) {
            tasks.push(function (templateSimplifyPage, index) {
                return function (callback) {
                    var rootReplaceGroup = THIS.templateSimplifyPageToGroup( templateSimplifyPage);
                    if(rootReplaceGroup){
                        THIS.simplifyMakeImagePage(libFunc,imgDirPath,relativeDir, rootReplaceGroup, index,imageSizes,replacePgsJson, callback);
                    }else{
                        var pageInfo = new common.PAGE_BACKGROUND_INFO_STRUCT(index, templateSimplifyPage.bg[0], templateSimplifyPage.bg[1],
                            templateSimplifyPage.bg[2], templateSimplifyPage.bg[3], templateSimplifyPage.bg[4],templateSimplifyPage.bg[5]);
                        callback(null, pageInfo);
                    }

                }
            }(templateSimplify[j],j) );
        }
        // 串行处理，所有文档生成完成后执行回调
        async.series(tasks, function (err, pageInfos) {
            pageInfos.sort(common.PAGE_STRUCT_SORT_FUNCTION);
            serialCallback(null,pageInfos);
        });

    });
}

// 生成模版的每页的缩略图
exports.makeImageOfTemplate = function(templateId,callback) {

}

// 取得 imageprocess.dll的jsonToImage函数
var g_libFunc =null;
exports.getImageProcessFuncs = function(){
    if(g_libFunc==null){
        var libname = 'imageprocess';
        if(os.platform()=='win32'){
            libname = 'imageprocess';
        }else{
            libname = 'libimageprocess.so';
        }
        var libpath =path.join(__dirname+'/../ext',libname);
        g_libFunc = ffi.Library(libpath, {
            'jsonToImage': [ 'bool', ['string','string','string','long',LongArray,'long','string'] ],
            'jsonToImageWithReplacePgsJson':[ 'bool', ['string','string','string','long',LongArray,'long','string','string'] ]
        });
    }
    return g_libFunc;
}

/*
 功能： 利用series来转换所有页
 参数：  pgs：模版或作品的页数据
         imageSizes：尺寸数组（存储能包含图片的正方形的边长）
         type：图片类型，见DEFINE.TIMAGE_TYPE
         replacePgsJson，（可为null）用此数据替换json中的图片，形如：
         serialCallback：回调，参数为common.PAGE_BACKGROUND_INFO_STRUCT数组

 生成文件例子：  第0页：   C:/nodejs/imageServer/images/2/20150909-0909-123090-232334/o0_100x100.png
                                C:/nodejs/imageServer/images/2/20150909-0909-123090-232334/o0_300x300.png
                 第1页：    C:/nodejs/imageServer/images/2/20150909-0909-123090-232334/o1_100x100.png
                                 C:/nodejs/imageServer/images/2/20150909-0909-123090-232334/o1_300x300.png
 */

exports.serialMakeImage = function(pgs,imageSizes, type,replacePgsJson,serialCallback){
    var libFunc = this.getImageProcessFuncs();

    var imgDirPath =path.join(__dirname,'../../ImageServer/public');
    var relativeDir = '/uploads/' +type + '/' +commonUtil.genUpDir();// 存放图片的根文件夹

    // 将所有页组成tasks，串行调用
    var THIS = this;
    var tasks = new Array();
    for (var j = 0; j < pgs.length; j++) {
        tasks.push(function (root, index) {
            return function (callback) {
                THIS.simplifyMakeImagePage(libFunc,imgDirPath,relativeDir, root, index,imageSizes,replacePgsJson, callback);
            }
        }(pgs[j].root,j) );
    }
    // 串行处理，所有文档生成完成后执行回调
    async.series(tasks, function (err, pageInfos) {
        pageInfos.sort(common.PAGE_STRUCT_SORT_FUNCTION);
        serialCallback(null,pageInfos);
    });

}
/*
 功能：将某页的数据生成缩略图
 参数：libFunc：动态链接库的ffi接口
     imgDirPath：图片服务器地址 例如：C:/nodejs/imageServer/images
     relativeDir：存放图片的相对路径 例如：/2/20150909-0909-123090-232334
     root：页的根对象（LayerObj对象）
     index：页码
     imageSizes：尺寸数组（存储能包含图片的正方形的边长）
     replacePgsJson，（可为null）用此数据替换json中的图片，形如：
     callback：回调，参数为common.PAGE_BACKGROUND_INFO_STRUCT对象，包含imageSizes中的一个尺寸的图片地址即可
     生成文件例子：      C:/nodejs/imageServer/images/2/20150909-0909-123090-232334/o0_100x100.png
                            C:/nodejs/imageServer/images/2/20150909-0909-123090-232334/o0_300x300.png
 */
exports.simplifyMakeImagePage = function(libFunc,imgDirPath, relativeDir,root, index,imageSizes, replacePgsJson,callback){
    // 生成图片
    var layerObj =  root;
    var jsonStr =  JSON.stringify(layerObj);

    // 尝试创建文件夹

    var targetDir =imgDirPath+ relativeDir;
    fs.mkdir(targetDir+"/", 0777, function(err){
        if(err && err.errno!=47) throw  err;

        var name="o"+index;
        var padding = index==0?2:0;
        var len = imageSizes.length;
        var sizes = new LongArray(len);
        for(var m=0;m<len;m++){
            sizes[m] = imageSizes[m];
        }
        console.log("simplifyMakeImagePage: jsonStr:"+jsonStr+"\n  targetDir: "+targetDir+"\n   imgDirPath:"+imgDirPath);
        if(replacePgsJson==null){
            libFunc.jsonToImage.async(jsonStr,name,targetDir,padding,sizes,len,imgDirPath, function (err, res) {
                var url = config.IMAGE_HOST+relativeDir+"/"+name+"_"+ sizes[1]+"x"+ sizes[1]+".png";
                console.log("async ffi jsonToImage is "+url);
                var pageInfo = new common.PAGE_BACKGROUND_INFO_STRUCT(index, layerObj.x, layerObj.y, layerObj.w, layerObj.h, layerObj.an, url);
                if(index==0){
                    pageInfo.thumUrl =    config.IMAGE_HOST+relativeDir+"/"+name+config.PADDING_FILE_SUFFIX +"_"+sizes[2]+"x"+ sizes[2]+".png";
                }

                callback(null, pageInfo);
            });
        }else{
            libFunc.jsonToImageWithReplacePgsJson.async(jsonStr,name,targetDir,padding,sizes,len,imgDirPath,replacePgsJson, function (err, res) {
                var url = config.IMAGE_HOST+relativeDir+"/"+name+"_"+ sizes[1]+"x"+ sizes[1]+".png";
                console.log("async ffi jsonToImageWithReplacePgsJson is "+url);
                var pageInfo = new common.PAGE_BACKGROUND_INFO_STRUCT(index, layerObj.x, layerObj.y, layerObj.w, layerObj.h, layerObj.an, url);
                if(index==0){
                    pageInfo.thumUrl =    config.IMAGE_HOST+relativeDir+"/"+name+config.PADDING_FILE_SUFFIX +"_"+sizes[2]+"x"+ sizes[2]+".png";
                }
                callback(null, pageInfo);
            });
        }

    });


}